package com.ruoyi.common.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class RenameImagesWithRule {
    public static void main(String[] args) {
        String baseDirectory = "E:\\workdate\\菜谱生产\\picnum\\hecheng"; // 替换为你的文件夹路径
        String logFile = "renamed_images_log.txt";       // 日志文件名

        File baseDir = new File(baseDirectory);

        if (baseDir.exists() && baseDir.isDirectory()) {
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(logFile))) {
                renameImagesInFolder(baseDir, writer);
                System.out.println("图片重命名完成，日志文件已保存到: " + new File(logFile).getAbsolutePath());
            } catch (IOException e) {
                System.err.println("写入日志文件时发生错误: " + e.getMessage());
            }
        } else {
            System.out.println("指定路径不存在或不是文件夹: " + baseDirectory);
        }
    }

    // 递归处理文件夹中的图片
    private static void renameImagesInFolder(File folder, BufferedWriter writer) throws IOException {
        for (File file : folder.listFiles()) {
            if (file.isDirectory()) {
                renameImagesInFolder(file, writer); // 递归处理子文件夹
            } else if (isImageFile(file)) {
                String newFileName = extractLastPartOfName(file.getName()) + getFileExtension(file);
                File newFile = new File(file.getParent(), newFileName);

                if (file.renameTo(newFile)) {
                    writer.write("原路径: " + file.getAbsolutePath() + " -> 新路径: " + newFile.getAbsolutePath());
                    writer.newLine();
                } else {
                    System.err.println("无法重命名文件: " + file.getAbsolutePath());
                }
            }
        }
    }

    // 判断文件是否为图片
    private static boolean isImageFile(File file) {
        String[] validExtensions = {".jpg", ".jpeg", ".png", ".bmp", ".gif", ".webp"};
        String fileName = file.getName().toLowerCase();
        for (String ext : validExtensions) {
            if (fileName.endsWith(ext)) {
                return true;
            }
        }
        return false;
    }

    // 提取文件名中下划线后的最后部分
    private static String extractLastPartOfName(String fileName) {
        int lastUnderscoreIndex = fileName.lastIndexOf("_");
        if (lastUnderscoreIndex != -1 && lastUnderscoreIndex < fileName.lastIndexOf(".")) {
            return fileName.substring(lastUnderscoreIndex + 1, fileName.lastIndexOf("."));
        }
        return fileName.substring(0, fileName.lastIndexOf(".")); // 如果没有下划线，保留文件名的主部分
    }

    // 获取文件扩展名
    private static String getFileExtension(File file) {
        String fileName = file.getName();
        int lastIndex = fileName.lastIndexOf(".");
        return (lastIndex > 0) ? fileName.substring(lastIndex) : "";
    }
}

